// 提供复用逻辑的函数
import { useIntersectionObserver } from '@vueuse/core'
import { ref, onUnmounted } from 'vue'
import dayjs from 'dayjs'
/**
 * 数据懒加载
 * @param {Element} target : dom元素;
 * @param {Function} apifn : api函数
 */
export const useLazyData = (apifn, limit = 0.1) => {
  const data = ref([])
  // 数据懒加载的dom元素
  const target = ref(null)
  const { stop } = useIntersectionObserver(
    target,
    ([{ isIntersecting }], observerElement) => {
      if (isIntersecting) {
        stop()
        apifn().then((res) => {
          console.log(res.result)
          data.value = res.result
        })
      }
    },
    {
      // 只要相交的比例大于limit才触发，注意是比例
      threshold: limit
    }
  )
  return { data, target }
}

export const paytime = () => {
  // 页面展示的时间
  const timetext = ref('')
  // 返回函数开启定时器
  let timer
  const start = (count) => {
    timer = setInterval(() => {
      if (count <= 0) {
        timetext.value = null
        clearInterval(timer)
      } else {
        timetext.value = dayjs.unix(count).format('mm分ss秒')
        count--
      }
    }, 1000)
  }
  // 销毁定时器
  onUnmounted(() => {
    clearInterval(timer)
  })
  return { timetext, start }
}
